<template>
  <div>
    <el-steps
      :active="step"
      simple>
      <el-step
        title="创建/选择试卷"
        icon="el-icon-s-claim" />
      <el-step
        title="考试配置"
        icon="el-icon-s-ticket" />
      <el-step
        title="发布考试"
        icon="el-icon-s-promotion" />
    </el-steps>
    <el-tabs
      style="margin-top: 50px"
      type="border-card"
      v-if="step === 1"
      v-model="activeName"
      @tab-click="handleClick">
      <el-tab-pane
        label="选择已有试卷"
        name="first">
        <tmpl-list
          :select-mode="true"
          @select="handleBack" />
      </el-tab-pane>
      <el-tab-pane
        label="创建新试卷"
        name="second">
        <tmpl-pre-create @confirm="handleCreate" />
      </el-tab-pane>
    </el-tabs>
    <!--    <div v-if="step===1">-->

    <!--      <h3>选择/创建试卷</h3>-->
    <!--      <el-card>-->

    <!--        <el-radio v-model="checkType" :label="1">选择已有试卷创建考试</el-radio>-->

    <!--        <div v-if="checkType===1">-->
    <!--          <tmpl-list :select-mode="true" @select="handleBack" />-->
    <!--        </div>-->

    <!--      </el-card>-->

    <!--      <el-card style="margin-top: 20px">-->
    <!--        <el-radio v-model="checkType" :label="2">新建试卷并创建考试</el-radio>-->
    <!--        <div v-if="checkType===2" style="padding-top: 20px">-->
    <!--          <tmpl-pre-create @confirm="handleCreate" />-->
    <!--        </div>-->
    <!--      </el-card>-->

    <!--    </div>-->

    <div
      v-if="step === 2"
      style="margin-left: -20px; margin-right: -20px; padding-top: 20px">
      <join1-form
        :title="createForm.title"
        :cat-id="createForm.catId"
        :join-type="createForm.joinType"
        :time-type="createForm.timeType"
        @back="handleBack" />
    </div>

    <div v-if="step === 3">
      <el-form
        ref="postForm"
        :model="postForm"
        :rules="rules"
        label-position="left"
        label-width="100px">
        <el-row :gutter="20">
          <el-col :span="18">
            <h3>考试设置</h3>

            <el-card>
              <el-row :gutter="50">
                <el-col :span="12">
                  <el-form-item
                    label="考试名称"
                    prop="title">
                    <el-input
                      v-model="postForm.title"
                      size="small" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="考试类型"
                    prop="examType">
                    <dic-list-select
                      v-model="postForm.examType"
                      dic-code="exam_type" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="及格分"
                    prop="qualifyScore">
                    <el-input-number
                      v-model="postForm.qualifyScore"
                      :max="tmplData.totalScore"
                      :precision="1"
                      size="small" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="考试时长"
                    prop="totalTime">
                    <el-input-number
                      v-model="postForm.totalTime"
                      :min="5"
                      :max="999"
                      size="small" />
                    <tool-tip msg="单位：分钟" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="限考次数"
                    prop="chance">
                    <el-input-number
                      v-model="postForm.chance"
                      size="small" />
                    <tool-tip msg="限制每个考生有几次考试机会，0为不限制" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="考试时间"
                    prop="dateRange">
                    <el-date-picker
                      v-model="postForm.dateRange"
                      size="small"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="积分数量"
                    prop="points">
                    <el-input-number
                      v-model="postForm.points"
                      size="small" />
                    <tool-tip msg="通过考试后获取积分数量，0为无" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="最低交卷时长">
                    <el-input-number
                      v-model="postForm.handMin"
                      size="small" />
                    <tool-tip msg="最低答题分钟数，未达到不允许交卷，0为不开启" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="允许迟到时长">
                    <el-input-number
                      v-model="postForm.lateMax"
                      size="small" />
                    <tool-tip msg="允许迟到的分钟数，注意：某段时间都可以考试的长期考试请设置为0" />
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="考前注意事项">
                    <el-input
                      v-model="postForm.content"
                      type="textarea"
                      maxlength="2000"
                      show-word-limit />
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="考试结果显示">
                    <el-radio-group
                      v-model="postForm.resultType"
                      size="small">
                      <el-radio :label="1">仅显示感谢文字</el-radio>
                      <el-radio :label="2">显示感谢文字+成绩</el-radio>
                      <el-radio :label="3">显示试卷明细</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>

                <el-col
                  v-if="postForm.resultType !== 3"
                  :span="24">
                  <el-form-item label="考后感谢文字">
                    <el-input
                      v-model="postForm.thanks"
                      type="textarea"
                      maxlength="2000"
                      show-word-limit />
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <div
                    style="background: #fbfbfb; padding: 10px; line-height: 36px; font-size: 14px">
                    <div style="font-weight: 700">考试权限</div>

                    <el-radio-group
                      v-model="postForm.openType"
                      size="small">
                      <el-radio :label="1">完全公开</el-radio>
                      <el-radio :label="2">部门开放</el-radio>
                      <el-radio :label="3">指定人员</el-radio>
                      <el-radio :label="9">口令密码</el-radio>
                      <el-radio :label="99">私密考试</el-radio>
                    </el-radio-group>

                    <div style="padding-top: 20px">
                      <div v-if="postForm.openType == 1">
                        <el-alert
                          title="开放的，任何人都可以进行考试！"
                          type="warning" />
                      </div>

                      <div v-if="postForm.openType == 2">
                        <depart-refs v-model="postForm.deptCodes" />
                      </div>

                      <div v-if="postForm.openType == 3">
                        <user-refs
                          :ref-id="postForm.id || tempId"
                          list-url="/api/exam/person/paging"
                          join-url="/api/exam/person/join"
                          remove-url="/api/exam/person/remove" />
                      </div>

                      <div v-if="postForm.openType == 9">
                        <el-form-item
                          label="考试密码"
                          prop="password">
                          <el-input
                            v-model="postForm.password"
                            size="small"
                            placeholder="输入考试密码" />
                        </el-form-item>
                      </div>

                      <div v-if="postForm.openType == 99">
                        <el-alert
                          title="私密考试不会出现在考试列表，用于学完课程考试，被课程模块关联的考试会自动变为私密状态！"
                          type="error" />
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-card>

            <h3>防作弊选项</h3>
            <el-card>
              <el-row>
                <el-col>
                  <el-form-item
                    label="学员答题设备设置"
                    label-width="300px">
                    <el-radio-group v-model="postForm.answerDevice">
                      <el-radio :label="0">可使用电脑或手机</el-radio>
                      <el-radio :label="1">仅电脑</el-radio>
                      <el-radio :label="2">仅手机</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>

                <el-col>
                  <el-form-item
                    label="人脸认证进入考试"
                    label-width="300px">
                    <el-switch
                      v-model="postForm.faceOn"
                      active-color="#13ce66"
                      inactive-color="#ff4949" />

                    &nbsp;开启后，需要人脸认证通过才可以进入考试
                  </el-form-item>
                </el-col>

                <el-col>
                  <el-form-item
                    label="答题时摄像头拍照监考（仅PC）"
                    label-width="300px">
                    <el-switch
                      v-model="postForm.camOn"
                      active-color="#13ce66"
                      inactive-color="#ff4949" />

                    <span v-if="postForm.camOn"
                      >&nbsp;学员开始答题后，每&nbsp;
                      <el-input-number
                        v-model="postForm.camInterval"
                        :min="1"
                        :max="30"
                        label="秒数"
                        size="mini" />
                      &nbsp;分钟抓拍一张学员答题照片&nbsp;
                    </span>
                  </el-form-item>
                </el-col>

                <el-col v-if="postForm.camOn">
                  <el-form-item
                    label="考试过程定时人脸识别（仅PC）"
                    label-width="300px">
                    <el-switch
                      v-model="postForm.faceCheck"
                      active-color="#13ce66"
                      inactive-color="#ff4949" />
                    对抓拍图片进行人脸识别，如果连续识别失败超过
                    <el-input-number
                      v-model="postForm.faceChance"
                      :min="0"
                      :max="postForm.totalTime / postForm.camInterval"
                      label="次数"
                      size="mini" />
                    次就强制交卷
                  </el-form-item>
                </el-col>

                <el-col>
                  <el-form-item
                    label="切屏后强制交卷"
                    label-width="300px">
                    <el-switch
                      v-model="postForm.leaveOn"
                      active-color="#13ce66"
                      inactive-color="#ff4949" />
                    <span v-if="postForm.leaveOn">
                      &nbsp;学员切换页面超过&nbsp;
                      <el-input-number
                        v-model="postForm.leaveCount"
                        :min="1"
                        :max="999"
                        label="秒数"
                        size="mini" />&nbsp;次后将被强制交卷，切换到其他页面&nbsp;
                      <el-input-number
                        v-model="postForm.leaveCheck"
                        :min="5"
                        :max="999"
                        label="秒数"
                        size="mini" />&nbsp;秒后即判定为切屏
                    </span>
                  </el-form-item>
                </el-col>

                <el-col>
                  <el-form-item
                    label="无操作强制交卷"
                    label-width="300px">
                    <el-switch
                      v-model="postForm.actionOn"
                      active-color="#13ce66"
                      inactive-color="#ff4949" />

                    <span v-if="postForm.actionOn">
                      &nbsp;答题时超过&nbsp;
                      <el-input-number
                        v-model="postForm.actionInterval"
                        :min="1"
                        :max="999"
                        label="秒数"
                        size="mini" />
                      &nbsp;秒学员没有任何交互则强制交卷&nbsp;
                    </span>
                  </el-form-item>

                  <el-form-item
                    label="开启考试水印（仅PC）"
                    label-width="300px">
                    <el-switch
                      v-model="postForm.waterMark"
                      active-color="#13ce66"
                      inactive-color="#ff4949" />
                  </el-form-item>

                  <el-form-item
                    label="显示考试错题"
                    label-width="300px">
                    <el-switch
                      v-model="postForm.showBook"
                      active-color="#13ce66"
                      inactive-color="#ff4949" />

                    多次考试时设置，杜绝作弊行为
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-col>

          <el-col :span="6">
            <h3>试卷信息</h3>
            <el-card style="font-size: 14px; line-height: 28px">
              <div>
                试卷标题：<el-link
                  :href="`/#/admin/tmpl/preview/${tmplData.id}`"
                  type="primary"
                  target="_blank"
                  >{{ tmplData.title }}</el-link
                >
              </div>
              <div>试卷总分：{{ tmplData.totalScore }}</div>
              <div>试题数量： {{ tmplData.quCount }}</div>
              <div>出卷人员：{{ tmplData.createBy_dictText }}</div>
              <div>创建时间：{{ tmplData.createTime }}</div>
            </el-card>
          </el-col>
        </el-row>

        <el-button
          type="primary"
          style="margin-top: 20px"
          @click="nextStep"
          >保存</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script>
import { uuid } from "vue-uuid";
import { fetchDetail, saveData } from "@/api/exam/exam";
import DicListSelect from "@/components/DicListSelect";
import ToolTip from "@/components/ToolTip";
import TmplPreCreate from "@/views/admin/tmpl/components/components/TmplPreCreate";
import Join1Form from "@/views/admin/tmpl/components/Join1Form";
import TmplList from "@/views/admin/tmpl";
import { apiFindSimple } from "@/api/tmpl/tmpl";
import UserRefs from "@/components/UserRefs";
import DepartRefs from "@/components/DepartRefs";
import { isDateRange } from "@/utils/validate";
import { mapGetters } from "vuex";

export default {
  name: "ExamDetail",
  components: { DepartRefs, UserRefs, TmplList, Join1Form, TmplPreCreate, ToolTip, DicListSelect },
  data() {
    return {
      activeName: "first",
      tempId: `temp_${uuid.v4()}`,
      step: 1,
      checkType: 1,

      tmplData: {},

      createForm: {
        data: {
          totalScore: 0,
        },
        title: null,
        joinType: 0,
        catId: null,
        timeType: 0,
      },

      // 表单
      postForm: {
        title: "",
        content: "",
        answerDevice: 0,
        password: "",
        tmplId: "",
        departIds: [],
        chance: 1,
        totalTime: 30,
        camInterval: 5,
        actionInterval: 300,
        leaveCount: 5,
        leaveCheck: 5,
        capture: 0,
        openType: 1,
        points: 0,
        price: 0,
        isCapture: true,
        resultType: 2,
        thanks: "感谢您的作答！",
        personList: [],
        camOn: false,
        leaveOn: false,
        actionOn: false,
        faceOn: false,
        faceCheck: false,
        faceInterval: 0,
        faceChance: 5,
        dateRange: ["", ""],
        qualifyScore: 0,
        startTime: "",
        endTime: "",
        waterMark: false,
        showBook: false,
      },
      rules: {
        title: [{ required: true, message: "考试名称不能为空！" }],
        open: [{ required: true, message: "考试权限不能为空！" }],

        qualifyScore: [{ required: true, message: "及格分不能为空！" }],

        totalTime: [{ required: true, message: "考试时长不能为空！" }],

        dateRange: [{ required: true, validator: isDateRange }],

        password: [{ required: true, message: "考试口令不能为空！" }],
        chance: [{ required: true, message: "考试次数不能为空，0为不限制！" }],
        examType: [{ required: true, message: "考试类型必须选择" }],
      },
    };
  },

  computed: {
    ...mapGetters(["siteData"]),
  },
  created() {
    // 选定创建试卷
    const tmplId = this.$route.params.tmplId;
    if (tmplId !== undefined && tmplId !== "0") {
      this.handleBack(tmplId);
      return;
    }

    const id = this.$route.params.id;
    if (id !== undefined) {
      this.fetchData(id);
    } else {
      this.postForm.openType = 1;
      this.postForm.joinType = 1;
    }
  },
  methods: {
    nextStep() {
      // 时间段覆盖
      this.postForm.startTime = this.postForm.dateRange[0];
      this.postForm.endTime = this.postForm.dateRange[1];

      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return;
        }
        this.$confirm("确实要提交保存吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.submitForm();
        });
      });
    },

    fetchData(id) {
      fetchDetail(id).then((res) => {
        const data = res.data;
        // 合并赋值
        Object.assign(this.postForm, data);
        // 起始时间
        if (data.startTime && data.endTime) {
          this.postForm.dateRange = [data.startTime, data.endTime];
        }
        this.handleBack(this.postForm.tmplId);
      });
    },

    submitForm() {
      // 赋值临时
      if (!this.postForm.id) {
        this.postForm.id = this.tempId;
      }

      saveData(this.postForm).then(() => {
        this.$notify({
          title: "成功",
          message: "考试保存成功！",
          type: "success",
          duration: 2000,
        });

        this.$router.push({ name: "ListExam" });
      });
    },

    handleCreate(data) {
      this.createForm = data;
      this.step = 2;
    },

    handleBack(id) {
      this.step = 3;
      this.postForm.tmplId = id;
      apiFindSimple(id).then((res) => {
        this.tmplData = res.data;
        if (!this.postForm.title) {
          this.postForm.title = res.data.title + " - 考试";
        }

        if (!this.postForm.qualifyScore) {
          this.postForm.qualifyScore = res.data.totalScore * 0.6;
        }
      });
    },
  },
};
</script>

<style scoped>
.score {
  float: right;
  font-weight: bold;
  color: #ff0000;
}

small {
  color: #666;
  line-height: 30px;
  margin-left: 10px;
}

::v-deep .left-box {
  height: calc(100vh - 170px);
  position: fixed;
  overflow: auto;
  clear: both;
}

::v-deep .left-box-normal {
  top: 170px;
}

::v-deep .left-box-scrolled {
  top: 20px;
  height: calc(100vh - 20px);
}
</style>
